package org.jugile.util;

import java.util.ArrayList;
import java.util.List;

/*

Copyright (C) 2007-2011 Jukka Rahkonen  email: jukka.rahkonen@iki.fi

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

/**
 * ""
 * 
 * @author jukka.rahkonen@iki.fi
 */
public class Timer {

	private final long start;
	private long end = 0L;
	private String className;
	private String methodName;
	protected String getClassName() { return className; }
	protected String getMethodName() { return methodName; }
	
	private long lastLap = 0L;
	private long lastLapStart = 0L;
	private String lastLapName = null;
	
	public Timer() {
		className = "";
		methodName = "";
		start = System.currentTimeMillis();		
	}
	
	public Timer(String className, String methodName) {
		start = System.currentTimeMillis();
		lastLapStart = start;
		this.className = className;
		this.methodName = methodName;
	}
	
	public long getDuration() {
		if (end == 0L) {
			if (lastLap > 0L) return lastLap;
			return 0L; // not stopped yet
		}
		return end - start;
	}
	
	public long stop() {
		end = System.currentTimeMillis();
		lastLapName = null;
		Profiler.stop(this);
		return end - start;
	}

	public long lap() { return lap(null);}	
	public long lap(String name) {
		long lap = System.currentTimeMillis();
		lastLap = lap - lastLapStart;
		lastLapStart = lap;
		lastLapName = name;
		Profiler.lap(this);
		return lastLap;
	}
	
	public long getLastLap() { return lastLap; }
	public String getLastLapName() { return lastLapName; }
	
	public String getKey() {
		String key = className + ":" + methodName;
		if (lastLapName != null) key += ":"+lastLapName;
		return key;
	}

	public String toString() {
		return ""+getDuration();
	}
	
}
